package DARCOServer.db;

import static DARCOShared.utils.Constants.*;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.Vector;

import javax.imageio.ImageIO;

import org.tmatesoft.sqljet.core.SqlJetException;
import org.tmatesoft.sqljet.core.table.ISqlJetTable;
import org.tmatesoft.sqljet.core.table.SqlJetDb;

import DARCOShared.utils.MD5;
import DARCOShared.utils.SecurityUtilities;

public class AccountDataToServerDB {

	//ACCOUNT_ID, ACCOUNT_EMAIL, ACCOUNT_NAME,ACCOUNT_SURNAME, ACCOUNT_USERNAME,
	//ACCOUNT_PASSWORD,ACCOUNT_LASTLOC, ACCOUNT_CREATION, ACCOUNT_AVATAR

	private Vector<Integer> accountID	= new Vector<Integer>();
	private Vector<String> accountEmail	= new Vector<String>();
	private Vector<String> accountName	= new Vector<String>();
	private Vector<String> accountSurname	= new Vector<String>();
	private Vector<String> accountUser	= new Vector<String>();
	private Vector<String> accountPwd	= new Vector<String>();
	private Vector<String> accountLastLoc	= new Vector<String>();
	private Vector<String> accountCreation	= new Vector<String>();
	private Vector<byte[]> accountAvatar	= new Vector<byte[]>();
	private Vector<byte[]> accountKeyPair	= new Vector<byte[]>();
	
	private String avatarPath=new String("./avatarImages/");
	
	private void createAccounts(){
		
		Integer counter=800;
		Calendar time = Calendar.getInstance();
		
		for(int n = 1; n < 10 ; n++ ){
			accountID.add(counter++);
			accountEmail.add("test00"+n+"@gmail.com");
			accountName.add("name00"+n);
			accountSurname.add("surname00"+n);
			accountUser.add("test00"+n);
			accountPwd.add(MD5.get("test00"+n));	
			accountLastLoc.add(null);
			time.set(2011, 12, n, 22, 14, 8);
			accountCreation.add(time.getTime().toString());
			accountAvatar.add(fileImageToBytes(avatarPath+"avatar_00"+(n)+".jpg"));
			accountKeyPair.add(SecurityUtilities.SerializeToBin(SecurityUtilities.generateRSAKeypair(1024)));
		}
	}
	
	public void putAccountsIntoServerDB(SqlJetDb db){
		try {
			ISqlJetTable accountTable = db.getTable(TABLE_NAME_ACCOUNTS);
			for (int i = 0; i < accountEmail.size(); i++) {
				accountTable.insert(accountID.get(i), accountEmail.get(i),accountName.get(i),accountSurname.get(i),
						accountUser.get(i),accountPwd.get(i),accountLastLoc.get(i),accountCreation.get(i), accountKeyPair.get(i) ,accountAvatar.get(i));
			}
						
			db.commit();
		} catch (SqlJetException e) {
			e.printStackTrace();
			}
				
		return;
		
	}
	
	public AccountDataToServerDB(){
		createAccounts();
	}
	

	private byte[] fileImageToBytes (String imageName){
		try{
			File fnew=new File(imageName);
			BufferedImage originalImage=ImageIO.read(fnew);
			ByteArrayOutputStream baos=new ByteArrayOutputStream();
			ImageIO.write(originalImage, "jpg", baos );
			return baos.toByteArray();	
		}catch(IOException e){
			System.out.println("Errorn on: "+imageName);
			return null;
			}
	}
	
}
